import OSS from 'ali-oss';
import path from 'path';
import fs from 'fs';
import { fileURLToPath } from 'url';
import {configDotenv} from "dotenv";
import pLimit from "p-limit";
configDotenv();
const __dirname = fileURLToPath(new URL('.', import.meta.url));

// OSS配置信息
const accessKeyId = process.env.OSS_ACCESS_KEY;
const accessKeySecret = process.env.OSS_ACCESS_SECRET;
const bucket = process.env.OSS_ACCESS_BUCKET;
const endpoint = process.env.OSS_ACCESS_ENDPONT;

// 创建OSS客户端实例
const client = new OSS({
    accessKeyId: accessKeyId,
    accessKeySecret: accessKeySecret,
    bucket: bucket,
    endpoint: endpoint
});

// 本地构建目录路径（假设是'dist'）
const localDir = path.join(__dirname, 'dist');

let uploadPromises = [];
// 递归上传文件到OSS
async function uploadDir(dir) {
    getUpload(dir)
    try {
        // 创建一个限制器，限制并发数为 10
        const limit = pLimit(10);
        // 将任务放入限制器中
        const limitedTasks = uploadPromises.map((task) => limit(task));
        await Promise.all(limitedTasks);
        console.log('All files uploaded successfully.');
    } catch (error) {
        console.error('Error during multi - thread upload:', error);
    }
}
function getUpload(dir){
    let files = fs.readdirSync(dir);
    for (let i = 0; i < files.length; i++) {
        let file = files[i];
        if(file.slice(-4) === '.map'){
            continue;
        }
        let localFile = path.join(dir, file);
        let remoteFile = localFile.replace(localDir, '');
        if (fs.statSync(localFile).isDirectory()) {
            getUpload(localFile);
        } else {
            uploadPromises.push(() => client.put(remoteFile, localFile));
        }
    }
}

uploadDir(localDir).then(() => {
    console.log('Deployment to OSS completed successfully.');
});